#include "usermanager.h"
#include <QTimer>
#include <QRegularExpression>
#include <QDebug>

namespace RestaurantSystem {

// 静态成员初始化
UserManager* UserManager::s_instance = nullptr;
const QString UserManager::DEFAULT_ADMIN_PASSWORD = "admin123";
const QString UserManager::PASSWORD_SALT_PREFIX = "RestaurantSystem_";

UserManager::UserManager(QObject* parent)
    : QObject(parent)
    , m_dataManager(nullptr)
    , m_sessionTimeoutMinutes(120)
    , m_sessionCheckTimer(new QTimer(this))
    , m_minPasswordLength(6)
    , m_requireUppercase(false)
    , m_requireLowercase(true)
    , m_requireDigits(true)
    , m_requireSpecialChars(false)
    , m_isInitialized(false)
{
    // 设置会话检查定时器
    m_sessionCheckTimer->setInterval(60000); // 每分钟检查一次
    connect(m_sessionCheckTimer, &QTimer::timeout, this, &UserManager::onSessionCheckTimer);
}

UserManager::~UserManager()
{
    if (m_sessionCheckTimer) {
        m_sessionCheckTimer->stop();
    }
}

UserManager& UserManager::instance()
{
    if (!s_instance) {
        s_instance = new UserManager();
    }
    return *s_instance;
}

bool UserManager::initialize()
{
    if (m_isInitialized) {
        return true;
    }
    
    try {
        m_dataManager = &DataManager::instance();
        
        // 首先初始化DataManager以加载所有数据
        if (!m_dataManager->initialize()) {
            ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                "Failed to initialize DataManager", 
                "UserManager::initialize");
            return false;
        }
        
        // 检查管理员配置是否存在，不存在则创建默认配置
        AdminConfig adminConfig = m_dataManager->getAdminConfig();
        if (!adminConfig.isValid()) {
            adminConfig = AdminConfig(generatePasswordHash(DEFAULT_ADMIN_PASSWORD));
            if (!m_dataManager->updateAdminConfig(adminConfig)) {
                ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                    "Failed to create default admin configuration", 
                    "UserManager::initialize");
                return false;
            }
            

        }
        
        m_isInitialized = true;
        m_sessionCheckTimer->start();
        

        
        return true;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::CRITICAL, 
            QString("UserManager initialization failed: %1").arg(e.what()), 
            "UserManager::initialize");
        return false;
    }
}

// ========================================================================
// 顾客管理
// ========================================================================

AuthResult UserManager::registerCustomer(const QString& username, const QString& password, const QString& email)
{
    if (!m_isInitialized) {
        return AuthResult::SYSTEM_ERROR;
    }
    
    // 验证用户名格式
    if (!isUsernameValid(username)) {
        emitAuthenticationFailed(AuthResult::INVALID_USERNAME, username);
        return AuthResult::INVALID_USERNAME;
    }
    
    // 检查用户名是否已存在（直接检查避免死锁）
    Customer existingCustomer = m_dataManager->getCustomerByUsername(username);
    if (existingCustomer.isValid()) {
        emitAuthenticationFailed(AuthResult::USER_ALREADY_EXISTS, username);
        return AuthResult::USER_ALREADY_EXISTS;
    }
    
    // 验证密码强度
    if (!isPasswordStrong(password)) {
        emitAuthenticationFailed(AuthResult::WEAK_PASSWORD, username);
        return AuthResult::WEAK_PASSWORD;
    }
    
    try {
        // 创建新顾客
        Customer customer(username, generatePasswordHash(password), email);
        customer.id = generateUserId();
        customer.plainPassword = password; // 存储明文密码供管理员查看
        customer.registrationDate = QDateTime::currentDateTime();
        
        // 保存到数据库
        if (m_dataManager->addCustomer(customer)) {
            // 立即保存数据到文件，确保持久化，创建备份
            m_dataManager->saveAllWithBackup();
            
            // 发送用户注册信号
            emit userRegistered(customer);

            return AuthResult::SUCCESS;
        } else {
            ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                QString("Failed to save customer: %1").arg(username), 
                "UserManager::registerCustomer", false); // 不显示给用户，UI层会处理
            return AuthResult::SYSTEM_ERROR;
        }
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during customer registration: %1").arg(e.what()), 
            "UserManager::registerCustomer", false); // 不显示给用户，UI层会处理
        return AuthResult::SYSTEM_ERROR;
    }
}

AuthResult UserManager::loginCustomer(const QString& username, const QString& password)
{
    if (!m_isInitialized) {
        return AuthResult::SYSTEM_ERROR;
    }
    
    try {
        // 查找用户
        Customer customer = m_dataManager->getCustomerByUsername(username);
        if (!customer.isValid()) {
            emitAuthenticationFailed(AuthResult::USER_NOT_FOUND, username);
            return AuthResult::USER_NOT_FOUND;
        }
        
        // 验证密码
        if (!verifyPassword(password, customer.passwordHash)) {
            emitAuthenticationFailed(AuthResult::INVALID_CREDENTIALS, username);
            return AuthResult::INVALID_CREDENTIALS;
        }
        
        // 更新最后登录时间
        customer.lastLoginDate = QDateTime::currentDateTime();
        m_dataManager->updateCustomer(customer);
        
        // 异步保存数据，避免在登录过程中阻塞
        QTimer::singleShot(0, [this]() {
            if (m_dataManager) {
                m_dataManager->saveAllWithBackup();
            }
        });
        
        // 创建会话
        createSession(customer.id, customer.username, false);
        

        
        return AuthResult::SUCCESS;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during customer login: %1").arg(e.what()), 
            "UserManager::loginCustomer");
        return AuthResult::SYSTEM_ERROR;
    }
}

bool UserManager::changeCustomerPassword(const QString& oldPassword, const QString& newPassword)
{
    if (!isLoggedIn() || isAdmin()) {
        return false;
    }
    
    try {
        Customer customer = m_dataManager->getCustomerById(getCurrentUserId());
        if (!customer.isValid()) {
            return false;
        }
        
        // 验证旧密码
        if (!verifyPassword(oldPassword, customer.passwordHash)) {
            return false;
        }
        
        // 验证新密码强度
        if (!isPasswordStrong(newPassword)) {
            return false;
        }
        
        // 更新密码
        customer.passwordHash = generatePasswordHash(newPassword);
        return m_dataManager->updateCustomer(customer);
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during password change: %1").arg(e.what()), 
            "UserManager::changeCustomerPassword");
        return false;
    }
}

bool UserManager::updateCustomerInfo(const Customer& customer)
{
    if (!isLoggedIn() || (getCurrentUserId() != customer.id && !isAdmin())) {
        return false;
    }
    
    return m_dataManager->updateCustomer(customer);
}

bool UserManager::deleteCustomerAccount(const QString& password)
{
    if (!isLoggedIn() || isAdmin()) {
        return false;
    }
    
    try {
        Customer customer = m_dataManager->getCustomerById(getCurrentUserId());
        if (!customer.isValid()) {
            return false;
        }
        
        // 验证密码
        if (!verifyPassword(password, customer.passwordHash)) {
            return false;
        }
        
        // 删除账户
        if (m_dataManager->deleteCustomer(customer.id)) {
            logout(); // 自动注销
            return true;
        }
        
        return false;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during account deletion: %1").arg(e.what()), 
            "UserManager::deleteCustomerAccount");
        return false;
    }
}

// ========================================================================
// 管理员管理
// ========================================================================

AuthResult UserManager::loginAdmin(const QString& password)
{
    if (!m_isInitialized) {
        return AuthResult::SYSTEM_ERROR;
    }
    
    try {
        AdminConfig adminConfig = m_dataManager->getAdminConfig();
        if (!adminConfig.isValid()) {
            emitAuthenticationFailed(AuthResult::SYSTEM_ERROR, "admin");
            return AuthResult::SYSTEM_ERROR;
        }
        
        // 验证密码
        if (!verifyPassword(password, adminConfig.passwordHash)) {
            emitAuthenticationFailed(AuthResult::INVALID_CREDENTIALS, "admin");
            return AuthResult::INVALID_CREDENTIALS;
        }
        
        // 创建管理员会话
        createSession("admin", "Administrator", true);
        

        
        return AuthResult::SUCCESS;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during admin login: %1").arg(e.what()), 
            "UserManager::loginAdmin");
        return AuthResult::SYSTEM_ERROR;
    }
}

bool UserManager::changeAdminPassword(const QString& oldPassword, const QString& newPassword)
{
    if (!isAdmin()) {
        return false;
    }
    
    try {
        AdminConfig adminConfig = m_dataManager->getAdminConfig();
        if (!adminConfig.isValid()) {
            return false;
        }
        
        // 验证旧密码
        if (!verifyPassword(oldPassword, adminConfig.passwordHash)) {
            return false;
        }
        
        // 验证新密码强度
        if (!isPasswordStrong(newPassword)) {
            return false;
        }
        
        // 更新密码
        adminConfig.passwordHash = generatePasswordHash(newPassword);
        adminConfig.lastModified = QDateTime::currentDateTime();
        
        return m_dataManager->updateAdminConfig(adminConfig);
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during admin password change: %1").arg(e.what()), 
            "UserManager::changeAdminPassword");
        return false;
    }
}

bool UserManager::resetAdminPassword(const QString& newPassword)
{
    if (!m_isInitialized) {
        return false;
    }
    
    try {
        // 验证新密码强度
        if (!isPasswordStrong(newPassword)) {
            return false;
        }
        
        AdminConfig adminConfig(generatePasswordHash(newPassword));
        adminConfig.lastModified = QDateTime::currentDateTime();
        
        bool result = m_dataManager->updateAdminConfig(adminConfig);
        if (result) {
            ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
                "Admin password has been reset", 
                "UserManager::resetAdminPassword");
        }
        
        return result;
    }
    catch (const std::exception& e) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
            QString("Exception during admin password reset: %1").arg(e.what()), 
            "UserManager::resetAdminPassword");
        return false;
    }
}

// ========================================================================
// 会话管理
// ========================================================================

void UserManager::updateSessionActivity()
{
    if (isLoggedIn()) {
        m_currentSession.updateActivity();
    }
}

void UserManager::logout()
{
    if (isLoggedIn()) {
        QString userId = m_currentSession.userId;
        clearSession();
        emit userLoggedOut(userId);
        

    }
}

void UserManager::checkSessionStatus()
{
    if (!isLoggedIn()) {
        return;
    }
    
    if (isSessionExpired()) {
        QString userId = m_currentSession.userId;
        clearSession();
        emit sessionExpired();
        emit userLoggedOut(userId);
        

    } else {
        // 检查是否即将过期(10分钟内)
        QDateTime expiryTime = m_currentSession.lastActivity.addSecs(m_sessionTimeoutMinutes * 60);
        QDateTime now = QDateTime::currentDateTime();
        int minutesLeft = now.secsTo(expiryTime) / 60;
        
        if (minutesLeft <= 10 && minutesLeft > 0) {
            emit sessionExpiring(minutesLeft);
        }
    }
}

// ========================================================================
// 密码和安全
// ========================================================================

bool UserManager::isPasswordStrong(const QString& password) const
{
    // 添加调试信息
    qDebug() << "[密码验证] 检查密码:" << password;
    qDebug() << "[密码验证] 密码长度:" << password.length() << "最小要求:" << m_minPasswordLength;
    qDebug() << "[密码验证] 要求大写:" << m_requireUppercase;
    qDebug() << "[密码验证] 要求小写:" << m_requireLowercase;
    qDebug() << "[密码验证] 要求数字:" << m_requireDigits;
    qDebug() << "[密码验证] 要求特殊字符:" << m_requireSpecialChars;
    
    if (password.length() < m_minPasswordLength) {
        qDebug() << "[密码验证] 失败: 长度不足";
        return false;
    }
    
    if (m_requireUppercase && !password.contains(QRegularExpression("[A-Z]"))) {
        qDebug() << "[密码验证] 失败: 缺少大写字母";
        return false;
    }
    
    if (m_requireLowercase && !password.contains(QRegularExpression("[a-z]"))) {
        qDebug() << "[密码验证] 失败: 缺少小写字母";
        return false;
    }
    
    if (m_requireDigits && !password.contains(QRegularExpression("[0-9]"))) {
        qDebug() << "[密码验证] 失败: 缺少数字";
        return false;
    }
    
    if (m_requireSpecialChars && !password.contains(QRegularExpression("[!@#$%^&*(),.?\":{}|<>]"))) {
        qDebug() << "[密码验证] 失败: 缺少特殊字符";
        return false;
    }
    
    qDebug() << "[密码验证] 成功: 密码符合所有要求";
    return true;
}

QString UserManager::getPasswordRequirements() const
{
    QStringList requirements;
    requirements << QString("至少%1个字符").arg(m_minPasswordLength);
    
    if (m_requireUppercase) {
        requirements << "包含大写字母";
    }
    
    if (m_requireLowercase) {
        requirements << "包含小写字母";
    }
    
    if (m_requireDigits) {
        requirements << "包含数字";
    }
    
    if (m_requireSpecialChars) {
        requirements << "包含特殊字符";
    }
    
    return requirements.join("、");
}

bool UserManager::isUsernameValid(const QString& username) const
{
    if (username.length() < 3 || username.length() > 20) {
        return false;
    }
    
    // 只允许字母、数字和下划线
    QRegularExpression regex("^[a-zA-Z0-9_]+$");
    return regex.match(username).hasMatch();
}

bool UserManager::isUsernameExists(const QString& username) const
{
    if (!m_dataManager) {
        return false;
    }
    
    Customer customer = m_dataManager->getCustomerByUsername(username);
    return customer.isValid();
}

QString UserManager::generatePasswordHash(const QString& password, const QString& salt)
{
    // 简化实现：统一使用固定盐值，确保生成和验证一致
    Q_UNUSED(salt);
    QString saltedPassword = PASSWORD_SALT_PREFIX + password;
    QByteArray hash = QCryptographicHash::hash(saltedPassword.toUtf8(), QCryptographicHash::Sha256);
    return hash.toHex();
}

bool UserManager::verifyPassword(const QString& password, const QString& hash)
{
    // 从哈希中提取盐值并验证
    // 简化实现：使用固定盐值前缀
    QString saltedPassword = PASSWORD_SALT_PREFIX + password;
    QByteArray computedHash = QCryptographicHash::hash(saltedPassword.toUtf8(), QCryptographicHash::Sha256);
    
    return computedHash.toHex() == hash.toLatin1();
}

QString UserManager::generateSalt()
{
    return QUuid::createUuid().toString().remove('{').remove('}').remove('-').left(16);
}

// ========================================================================
// 辅助方法
// ========================================================================

QString UserManager::getAuthResultMessage(AuthResult result)
{
    switch (result) {
    case AuthResult::SUCCESS:
        return "认证成功";
    case AuthResult::INVALID_CREDENTIALS:
        return "用户名或密码错误";
    case AuthResult::USER_NOT_FOUND:
        return "用户不存在";
    case AuthResult::USER_ALREADY_EXISTS:
        return "用户名已存在";
    case AuthResult::WEAK_PASSWORD:
        return "密码强度不足";
    case AuthResult::INVALID_USERNAME:
        return "用户名格式无效";
    case AuthResult::SYSTEM_ERROR:
        return "系统错误";
    default:
        return "未知错误";
    }
}

QString UserManager::generateUserId()
{
    return "user_" + QUuid::createUuid().toString().remove('{').remove('}').remove('-');
}

// ========================================================================
// 私有方法
// ========================================================================

void UserManager::createSession(const QString& userId, const QString& username, bool isAdmin)
{
    m_currentSession = UserSession(userId, username, isAdmin);
    emit userLoggedIn(userId, username, isAdmin);
}

void UserManager::clearSession()
{
    m_currentSession = UserSession();
}

void UserManager::emitAuthenticationFailed(AuthResult result, const QString& username)
{
    emit authenticationFailed(result, username);
    ErrorHandler::instance().handleError(ErrorLevel::WARNING, 
        QString("Authentication failed for user '%1': %2").arg(username, getAuthResultMessage(result)), 
        "UserManager::emitAuthenticationFailed", false); // 不显示给用户，UI层会处理
}

// ========================================================================
// 槽函数
// ========================================================================

void UserManager::onSessionCheckTimer()
{
    checkSessionStatus();
}

// ============================================================================
// 用户信息管理 (新增方法实现)
// ============================================================================

Customer UserManager::getUserById(const QString& userId) {
    if (userId.isEmpty()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "用户ID不能为空", "UserManager::getUserById", false);
        return Customer(); // 返回无效的Customer对象
    }
    
    const QList<Customer>& customers = m_dataManager->getAllCustomers();
    for (const Customer& customer : customers) {
        if (customer.id == userId) {
            return customer;
        }
    }
    
        ErrorHandler::instance().handleError(ErrorLevel::ERROR,
                         QString("未找到用户ID: %1").arg(userId), "UserManager::getUserById", false);
    return Customer(); // 返回无效的Customer对象
}

QString UserManager::getUserIdByUsername(const QString& username) {
    if (username.isEmpty()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "用户名不能为空", "UserManager::getUserIdByUsername", false);
        return QString();
    }

    const QList<Customer>& customers = m_dataManager->getAllCustomers();
    for (const Customer& customer : customers) {
        if (customer.username == username) {
            return customer.id;
        }
    }

    ErrorHandler::instance().handleError(ErrorLevel::ERROR,
                         QString("未找到用户名: %1").arg(username), "UserManager::getUserIdByUsername", false);
    return QString();
}

AuthResult UserManager::updateUserInfo(const QString& userId, const Customer& updatedInfo) {
    if (userId.isEmpty()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "用户ID不能为空", "UserManager::updateUserInfo", false);
        return AuthResult::INVALID_CREDENTIALS;
    }
    
    if (!updatedInfo.isValid()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                                 QString("用户信息无效: %1").arg(updatedInfo.getValidationError()), "UserManager::updateUserInfo", false);
        return AuthResult::INVALID_CREDENTIALS;
    }
    
    QList<Customer> customers = m_dataManager->getAllCustomers();
    bool found = false;
    
    for (Customer& customer : customers) {
        if (customer.id == userId) {
            // 保持ID、密码和注册时间不变
            QString originalId = customer.id;
            QString originalPasswordHash = customer.passwordHash;
            QDateTime originalRegistrationDate = customer.registrationDate;
            
            customer = updatedInfo;
            customer.id = originalId;
            customer.passwordHash = originalPasswordHash;
            customer.registrationDate = originalRegistrationDate;
            customer.lastLoginDate = QDateTime::currentDateTime(); // 更新最后活动时间
            
            found = true;
            break;
        }
    }
    
    if (!found) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, 
                                 QString("未找到用户ID: %1").arg(userId), "UserManager::updateUserInfo", false);
        return AuthResult::USER_NOT_FOUND;
    }
    
    // 保存到数据管理器 - 需要找到正确的方法
    m_dataManager->updateCustomer(updatedInfo);
    m_dataManager->saveAll();
    
    emit userInfoUpdated(userId);
    return AuthResult::SUCCESS;
}

AuthResult UserManager::changePassword(const QString& userId, const QString& oldPassword, const QString& newPassword) {
    if (userId.isEmpty()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "用户ID不能为空", "UserManager::changePassword", false);
        return AuthResult::INVALID_CREDENTIALS;
    }
    
    if (oldPassword.isEmpty() || newPassword.isEmpty()) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "密码不能为空", "UserManager::changePassword", false);
        return AuthResult::INVALID_CREDENTIALS;
    }
    
    // 验证新密码强度
    if (!validatePasswordStrength(newPassword)) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "新密码强度不足", "UserManager::changePassword", false);
        return AuthResult::WEAK_PASSWORD;
    }
    
    // 获取用户并验证
    Customer customer = getUserById(userId);
    if (customer.id.isEmpty()) {
        return AuthResult::USER_NOT_FOUND;
    }
    
    // 验证原密码
    QString oldPasswordHash = generatePasswordHash(oldPassword);
    if (customer.passwordHash != oldPasswordHash) {
        ErrorHandler::instance().handleError(ErrorLevel::ERROR, "原密码错误", "UserManager::changePassword", false);
        return AuthResult::INVALID_CREDENTIALS;
    }
    
    // 更新密码
    customer.passwordHash = generatePasswordHash(newPassword);
    customer.plainPassword = newPassword; // 同时更新明文密码
    customer.lastLoginDate = QDateTime::currentDateTime(); // 更新最后活动时间
    
    // 保存到数据管理器
    m_dataManager->updateCustomer(customer);
    m_dataManager->saveAll();
    
    emit passwordChanged(userId);
    return AuthResult::SUCCESS;
}

bool UserManager::validatePasswordStrength(const QString& password) {
    if (password.length() < m_minPasswordLength) {
        return false;
    }
    
    if (m_requireUppercase) {
        QRegularExpression upperRegex("[A-Z]");
        if (!upperRegex.match(password).hasMatch()) {
            return false;
        }
    }
    
    if (m_requireLowercase) {
        QRegularExpression lowerRegex("[a-z]");
        if (!lowerRegex.match(password).hasMatch()) {
            return false;
        }
    }
    
    if (m_requireDigits) {
        QRegularExpression digitRegex("[0-9]");
        if (!digitRegex.match(password).hasMatch()) {
            return false;
        }
    }
    
    if (m_requireSpecialChars) {
        QRegularExpression specialRegex("[!@#$%^&*()_+\\-=\\[\\]{};':\"\\\\|,.<>\\/?]");
        if (!specialRegex.match(password).hasMatch()) {
            return false;
        }
    }
    
    return true;
}

bool UserManager::verifyCurrentUserPassword(const QString& userId, const QString& password) {
    if (userId.isEmpty() || password.isEmpty()) {
        return false;
    }
    
    // 获取用户信息
    Customer customer = getUserById(userId);
    if (customer.id.isEmpty()) {
        return false;
    }
    
    // 验证密码
    return verifyPassword(password, customer.passwordHash);
}

// ============================================================================
// 管理员用户管理功能实现
// ============================================================================

QList<Customer> UserManager::getAllCustomers()
{
    if (!m_isInitialized) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 尝试获取用户列表但管理器未初始化", "UserManager::getAllCustomers");
        return QList<Customer>();
    }
    
    if (!isAdmin()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 非管理员尝试获取所有用户列表", "UserManager::getAllCustomers");
        return QList<Customer>();
    }
    
    return m_dataManager->getAllCustomers();
}

bool UserManager::resetCustomerPassword(const QString& customerId, const QString& newPassword)
{
    if (!m_isInitialized) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 尝试重置密码但管理器未初始化", "UserManager::resetCustomerPassword");
        return false;
    }
    
    if (!isAdmin()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 非管理员尝试重置用户密码", "UserManager::resetCustomerPassword");
        return false;
    }
    
    if (customerId.isEmpty()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 重置密码时用户ID为空", "UserManager::resetCustomerPassword");
        return false;
    }
    
    // 获取用户信息
    Customer customer = getUserById(customerId);
    if (customer.id.isEmpty()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, QString("UserManager: 未找到ID为 %1 的用户").arg(customerId), "UserManager::resetCustomerPassword");
        return false;
    }
    
    // 使用默认密码或指定密码
    QString passwordToSet = newPassword.isEmpty() ? "abc123456" : newPassword;
    
    // 验证新密码强度
    if (!isPasswordStrong(passwordToSet)) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 重置密码不符合强度要求", "UserManager::resetCustomerPassword");
        return false;
    }
    
    // 生成新的密码哈希
    QString newPasswordHash = generatePasswordHash(passwordToSet);
    customer.passwordHash = newPasswordHash;
    customer.plainPassword = passwordToSet; // 同时存储明文密码供管理员查看
    
    // 更新用户信息
    try {
        m_dataManager->updateCustomer(customer);
        m_dataManager->saveAll();
        
        emit passwordChanged(customerId);
        ErrorHandler::instance().logMessage(ErrorLevel::INFO, QString("UserManager: 成功重置用户 %1 的密码").arg(customer.username), "UserManager::resetCustomerPassword");
        return true;
    } catch (const std::exception& e) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, QString("UserManager: 重置密码时保存失败: %1").arg(e.what()), "UserManager::resetCustomerPassword");
        return false;
    }
}

bool UserManager::updateCustomerStatus(const QString& customerId, bool active)
{
    if (!m_isInitialized) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 尝试更新用户状态但管理器未初始化", "UserManager::updateCustomerStatus");
        return false;
    }
    
    if (!isAdmin()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 非管理员尝试更新用户状态", "UserManager::updateCustomerStatus");
        return false;
    }
    
    if (customerId.isEmpty()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 更新状态时用户ID为空", "UserManager::updateCustomerStatus");
        return false;
    }
    
    // 获取用户信息
    Customer customer = getUserById(customerId);
    if (customer.id.isEmpty()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, QString("UserManager: 未找到ID为 %1 的用户").arg(customerId), "UserManager::updateCustomerStatus");
        return false;
    }
    
    // 注意：当前Customer模型中没有active字段，这里只是占位实现
    // 实际项目中可能需要扩展Customer模型或添加状态管理
    ErrorHandler::instance().logMessage(ErrorLevel::INFO, QString("UserManager: 用户 %1 状态设置为 %2").arg(customer.username).arg(active ? "活跃" : "非活跃"), "UserManager::updateCustomerStatus");
    
    // 这里可以扩展Customer模型来支持状态管理
    // customer.isActive = active;
    // m_dataManager->updateCustomer(customer);
    // m_dataManager->saveAll();
    
    return true;
}

UserManager::CustomerStatistics UserManager::getCustomerStatistics()
{
    CustomerStatistics stats;
    
    if (!m_isInitialized) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 尝试获取统计信息但管理器未初始化", "UserManager::getCustomerStatistics");
        return stats;
    }
    
    if (!isAdmin()) {
        ErrorHandler::instance().logMessage(ErrorLevel::ERROR, "UserManager: 非管理员尝试获取用户统计", "UserManager::getCustomerStatistics");
        return stats;
    }
    
    QList<Customer> allCustomers = m_dataManager->getAllCustomers();
    stats.totalCustomers = allCustomers.size();
    
    QDateTime now = QDateTime::currentDateTime();
    QDateTime weekAgo = now.addDays(-7);
    QDateTime monthAgo = now.addDays(-30);
    
    for (const Customer& customer : allCustomers) {
        // 检查活跃用户 (最近30天有登录)
        if (customer.lastLoginDate.isValid() && customer.lastLoginDate >= monthAgo) {
            stats.activeCustomers++;
        } else {
            stats.inactiveCustomers++;
        }
        
        // 检查新用户 (最近7天注册)
        if (customer.registrationDate.isValid() && customer.registrationDate >= weekAgo) {
            stats.newCustomers++;
        }
    }
    
    ErrorHandler::instance().logMessage(ErrorLevel::INFO, QString("UserManager: 用户统计 - 总数:%1, 活跃:%2, 新用户:%3, 非活跃:%4")
                         .arg(stats.totalCustomers)
                         .arg(stats.activeCustomers)
                         .arg(stats.newCustomers)
                         .arg(stats.inactiveCustomers), "UserManager::getCustomerStatistics");
    
    return stats;
}

} // namespace RestaurantSystem
